package com.neutech.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.neutech.config.NeueduException;
import com.neutech.core.TeachUtil;
import com.neutech.entity.Student;
import com.neutech.mapper.StudentMapper;
import com.neutech.service.StudentService;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.management.Query;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 学生表 服务层实现。
 *
 * @author Administrator
 * @since 2025-02-08
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>  implements StudentService{
    @Resource
    PasswordEncoder passwordEncoder;
    public Student getByIdCard(String idCard) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("id_card", idCard);
        return this.getOne(wrapper);
    }

    @Override
    public List<Student> list(Integer gradeId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("grade_id", gradeId);
        return this.list(wrapper);
    }
    @Override
    public boolean upload(MultipartFile file, Integer gradeId) throws CsvValidationException, IOException {
        CSVReader reader = new CSVReader(new InputStreamReader(file.getInputStream(), "GBK"));
        String[] line = reader.readNext();
        List<Student> list = new ArrayList<>();
        List<String> errorList = new ArrayList<>();
        int i = 1;
        while((line = reader.readNext()) != null) {
            Student student = new Student();
            String no = line[0].trim();
            student.setNo(no);
            String name = line[1].trim();
            if (name.trim().length() > 10 || name.isEmpty()) {
                errorList.add(String.format("第%s行: 姓名必须1~10个字符", i));
            }
            student.setName(name);
            String school = line[2].trim();
            if (school.trim().length() > 64 || school.isEmpty()) {
                errorList.add(String.format("第%s行: 毕业院校必须1~64个字符", i));
            }
            student.setSchool(school);
            String major = line[3].trim();
            if (major.trim().length() > 20 || major.isEmpty()) {
                errorList.add(String.format("第%s行: 专业必须1~20个字符", i));
            }
            student.setMajor(major);
            String qualification = line[4].trim();
            if (qualification.trim().length() > 20 || qualification.isEmpty()) {
                errorList.add(String.format("第%s行: 学历必须1~20个字符", i));
            }
            student.setQualification(qualification);
            String englishLevel = line[5].trim();
            if (englishLevel.trim().length() > 10 || englishLevel.isEmpty()) {
                errorList.add(String.format("第%s行: 英语等级必须1~10个字符", i));
            }
            student.setEnglishLevel(englishLevel);
            String otherLanguage = line[6].trim();
            if (otherLanguage.trim().length() > 20 || otherLanguage.isEmpty()) {
                errorList.add(String.format("第%s行: 其他语言必须1~20个字符", i));
            }
            student.setOtherLanguage(otherLanguage);
            String graduationDate = line[7].trim();
            try {
                student.setGraduationDate(LocalDate.parse(graduationDate, DateTimeFormatter.ofPattern("yyyy-M-d")));
            } catch (Exception ex) {
                 errorList.add(String.format("第%s行: 毕业时间是 年-月-日格式", i));
            }
            String phone = line[8].trim();
            if (!Pattern.matches("^1[3-9]\\d{9}$", phone)) {
                errorList.add(String.format("第%s行: 联系方式不合法(只能是手机号)", i));
            }
            student.setPhone(phone);
            String email = line[9].trim();
            if (!Pattern.matches("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*", email)) {
                errorList.add(String.format("第%s行: 邮箱不合法", i));
            }
            student.setEmail(email);
            student.setPassword(this.passwordEncoder.encode(phone));
            student.setGradeId(gradeId);
            list.add(student);
            i++;
        }
        if (!errorList.isEmpty()) {
            throw new NeueduException(errorList.toString().replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\,", "\n"));
        }
        return this.saveOrUpdateBatch(list);
    }

    @Override
    public boolean add(Student student) {
        student.setPassword(this.passwordEncoder.encode(student.getPhone()));
        return this.save(student);
    }

    @Override
    public boolean del(Integer id, Boolean active) {
        return this.updateById(new Student(id, active));
    }

    @Override
    public boolean check(Integer id, String field, String value) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq(field, value);
        if (null != id) {
            wrapper.ne("id", id);
        }
        return this.count(wrapper) == 0;
    }

    @Override
    public long count(Integer gradeId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("grade_id", gradeId);
        return this.count(wrapper);
    }
}
